<?php

namespace app\controller\adminapi\platform\app;

use app\controller\adminapi\platform\PlatformController;
use hiduoke\services\douyinMinApp\DouyinMinAppServer;
use hiduoke\services\FormBuilder as Form;
use think\facade\Cache;
use think\App;

class MinAppDouyinOpen extends PlatformController
{
    public $DY = null;

    public $authorizer_access_token;


    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->platform_app_id = input('platform_app_id', 0);
        if ($this->platform_app_id) {
            $this->DY = new DouyinMinAppServer($this->platform_app_id);
            $this->authorizer_access_token = $this->DY->get_authorizer_access_token();
        }
    }

    // 获取小程序版本列表信息
    public function getDouyinVersionsByAppId()
    {
        $res = $this->DY->getOpenApi()->versions($this->authorizer_access_token);
        Cache::delete('version_app_id_' .  $this->platform_app_id );
        if ($res['errno'] == 0) {
            return $this->success('', $res['data']);
        } else {
            return $this->error($res['message']);
        }
    }

    // 提交代码
    public function uploadDouyinVersion($desc = '')
    {
        $open = $this->DY->getPlatformAppOpen();
        $template_id = $open['config']['template_id'] ?? '';
        $user_version = $open['config']['user_version'] ?? '';
        $user_desc = $open['config']['desc'] ?? '新版本';
        if (!$template_id || !$user_version) {
            return $this->error('当前代码不存在，请联系管理员');
        }
        $user_desc = $desc ?: $user_desc;
        $data = [
            'template_id'  => intval($template_id),
            'user_desc'    => $user_desc,
            'user_version' => $user_version,
            'ext_json'     => json_encode([
                'extEnable' => true,
                'ext'       => [
                    'baseUrl'             => request()->domain(),
                    'plaid'               => $this->DY->plaid,
                    'platform_appid'      => $this->DY->platform_app_id,
                    'addon_name'          => $this->DY->addon_name,
                    'authorization_appid' => $this->DY->authorization_appid
                ]
            ]),
        ];
        $res = $this->DY->getOpenApi()->upload($this->authorizer_access_token, $data);
        if ($res['errno'] == 0) {
            $app = $this->DY->getPlatformApp();
            $app->version = $user_version;
            $app->save();
            return $this->success('提交成功');
        } else {
            return $this->error($res['message']);
        }
    }

    // 提交审核
    public function auditDouyinVersion($data = [])
    {
        $res = $this->DY->getOpenApi()->audit($this->authorizer_access_token, $data);

        if ($res['errno'] == 0) {
            return $this->success('提交成功');
        } else {
            return $this->error($res['message']);
        }
    }

    // 撤回审核
    public function revokeAuditDouyinVersion()
    {
        $res = $this->DY->getOpenApi()->revoke_audit($this->authorizer_access_token);
        if ($res['errno'] == 0) {
            return $this->success('撤回成功');
        } else {
            return $this->error($res['message']);
        }
    }

    // 发布代码
    public function releaseDouyinVersion()
    {
        $res = $this->DY->getOpenApi()->release($this->authorizer_access_token);
        if ($res['errno'] == 0) {
            return $this->success('发布成功');
        } else {
            return $this->error($res['message']);
        }
    }

    /**
     * 获取新版本信息
     */
    public function getDouyinNewVersion()
    {
        $open = $this->DY->getPlatformAppOpen();
        $app = $this->DY->getPlatformApp();
        $new_version = $open['config']['user_version'] ?? false;
        $desc = $open['config']['user_desc'] ?? '新版本';
        $data = [
            'version'     => $app['version'],
            'new_version' => $new_version,
            'desc'        => $desc,
        ];
        if ($new_version && $app['version'] != $new_version) {
            // 版本有差异
            $data['update'] = true;
        } else {
            $data['update'] = false;
        }
        return $this->success('', $data);
    }

    /**
     * 获取二维码
     */
    public function getDouyinQrcode($version, $path = '')
    {
        $image = $this->DY->getQrcode($version, $path);
        return $this->success('', [
            'qr_code_url' => 'data:image/png;base64,' . base64_encode($image)
        ]);
    }

    /**
     * 获取授权地址
     * @param $default_app_id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getDouyinGenUrl($default_app_id = 0)
    {
        $link = $this->DY->getLink();
        if ($link) {
            return $this->success('', ['url' => $link]);
        } else {
            return $this->error($this->DY->err);
        }
    }

    /**
     * 获取抖音小程序信息
     * Create by :  刘泓宾<514660094@qq.com>
     * @return \think\response\Json
     */
    public function getDouyinAppInfo()
    {
        $res = $this->DY->info();
        if ($res['errno'] == 0) {
            return $this->success('', $res['data']);
        } else {
            return $this->error($res['message']);
        }
    }


    public function getBindDomainForm()
    {
        $params = http_build_query([
            'component_appid'         => $this->DY->getOpenApi()->component_appid,
            'authorizer_access_token' => $this->DY->get_authorizer_access_token(),
        ]);
        $res = $this->DY->getOpenApi()
            ->httpPost("https://open.microapp.bytedance.com/openapi/v1/microapp/app/modify_server_domain?" . $params, [
                'action' => 'get',
            ]);
        $row = [];
        if ($res['errno'] == 0 && $res['message'] == 'success') {
            $data = $res['data'];
            foreach ($data as $key => $domains) {
                $_domains = [];
                foreach ($domains as $k => $domain) {
                    $_domains[] = [
                        'domain' => $domain
                    ];
                }
                $row[$key] = $_domains;
            }
        } else {
            return $this->error('当前获取绑定域名失败，请检查配置', $res);
        }
        $rule = array();
        //创建表单
        $form = Form::createForm("/adminapi/platform/min_app/douyin_open/bindDomain")->setMethod("POST");
        $rule[] = Form::hidden('platform_app_id', $this->platform_app_id);
        //新增表单
        $rule[] = Form::group('request', 'request域名', $row['request'])->rule([
            Form::input('domain', '域名')
        ]);
        $rule[] = Form::group('socket', 'socket域名', $row['socket'])->rule([
            Form::input('domain', '域名')
        ]);
        $rule[] = Form::group('upload', '上传文件域名', $row['upload'])->rule([
            Form::input('domain', '域名')
        ]);
        $rule[] = Form::group('download', '下载文件域名', $row['download'])->rule([
            Form::input('domain', '域名')
        ]);
        $form->setTitle("域名配置")->setRule($rule);
        return $this->success("", Form::getFormData($form), $res);
    }

    // 修改域名
    public function bindDomain()
    {
        $formData = getFormData();
        $platform_app_id = $formData['platform_app_id'];
        $this->DY = new DouyinMinAppServer($platform_app_id);
        $data = [];
        foreach ($formData as $key => $domains) {
            $_domains = [];
            if (is_array($domains)) {
                foreach ($domains as $k => $value) {
                    $_domains[] = $value['domain'];
                }
                $data[$key] = $_domains;
            }
        }
        $data['action'] = 'set';
        $params = http_build_query([
            'component_appid'         => $this->DY->getOpenApi()->component_appid,
            'authorizer_access_token' => $this->DY->get_authorizer_access_token(),
        ]);
        $res = $this->DY->getOpenApi()
            ->httpPost("https://open.microapp.bytedance.com/openapi/v1/microapp/app/modify_server_domain?" . $params, $data);
        if ($res['errno'] == 0) {
            return $this->success("配置成功", $res);
        } else {
            return $this->error($res['message']);
        }
    }

}
